package com.example.list;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.utils.MyWebView;
/*Android WebView —— Java 与 JavaScript 交互总结
https://zhuanlan.zhihu.com/p/149985867*/
public class WebViewActivity2 extends AppCompatActivity {

    private MyWebView myWebView;
    /**
     * 文件夹根目录 file协议 文件路径
     * 要将文件放到正确的路径，否则会报 file_not_found。
     */
    String url1 = "file:///storage/emulated/0/js_java_interaction.html";
    String url2="file:///android_asset/baidu.html";
    String url;
    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view2);
        myWebView = (MyWebView)findViewById(R.id.myWebview);

        myWebView.getSettings().setAllowFileAccess(true);

        url=url1;
        myWebView.loadUrl(url);
// 测试路径用的
/*        String mkdir = Environment.getExternalStorageDirectory() + "/" + "11.txt";
        File file = new File(mkdir);
        if(file.exists()){
            System.out.println("文件夹已存在");
        }else{
            file.mkdirs();
            System.out.println("新建成功");
        }
        System.out.println("mkdir = " + mkdir);*/

        myWebView.addJavascriptInterface(this, "main");
        myWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message,JsResult result) {
                //Required functionality here
                return super.onJsAlert(view, url, message, result);
            }
        });


    }

    public void javaCallJs(View v){
        myWebView.loadUrl("javascript:javaCallJs(" + "'Message From Java'" + ")");
    }

    @JavascriptInterface
    public void jsCallJava(String message){
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    public void jsFalse(View view) {
        myWebView.setBoolean(false);
        myWebView.loadUrl(url);

    }

    public void jsTrue(View view) {
        myWebView.setBoolean(true);
        myWebView.loadUrl(url);
    }
}